package com.lishanyang.hibernate.dao;



import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.io.Serializable;


public class BaseHibernateDAO {
    //添加数据
    protected void add(Object object){
        Transaction tran =null;
        /*
         * 获取Session
         */
        //Configuration对象对应于Hibernate的基本配置信息和对象关系映射文件
        Configuration configuration = new Configuration().configure();
        //创建一个SessionFactory对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //创建一个Session对象
        try ( sessionFactory) {
            Session session = sessionFactory.openSession();
            tran = session.beginTransaction();
            //持久化操作
            session.save(object);
            //提交事务
            tran.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (tran != null) {
                tran.rollback();
            }
        }
    }


    /*
    *加载数据
    * */
    protected Object get(Class cla , Serializable id){
        Object object =null;
        /*
         * 获取Session
         */
        //Configuration对象对应于Hibernate的基本配置信息和对象关系映射文件
        Configuration configuration = new Configuration().configure();
        //创建一个SessionFactory对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        //创建一个Session对象
        try ( sessionFactory ) {
            Session session = sessionFactory.openSession();
            object = session.get(cla , id);

        } catch (HibernateException e) {
            e.printStackTrace();

        }
        Object object1 = object;
        return object1;
    }

    /*
    * 删除数据
    *
    * */
    protected void delete(Object object){
        Transaction tran=null;
        Configuration configuration=new Configuration().configure();
        SessionFactory sessionFactory=configuration.buildSessionFactory();
        try ( sessionFactory ) {
            Session session = sessionFactory.openSession();
            tran = session.beginTransaction();
            session.delete(object);
            tran.commit();
        } catch (HibernateException e) {
            if (tran != null) {
                tran.rollback();
            }
        }
    }

    /*
    * 修改数据
    * */
    protected void update(Object object){
        Transaction tran=null;
        Configuration configuration=new Configuration().configure();
        SessionFactory sessionFactory=configuration.buildSessionFactory();
        try ( sessionFactory ) {
            Session session = sessionFactory.openSession();
            tran = session.beginTransaction();
            session.update(object);
            tran.commit();
        } catch (HibernateException e) {
            if (tran != null) {
                tran.rollback();
            }
            e.printStackTrace();
        }
    }


}
